import pandas as pd
import numpy as np
from scipy import stats

def process(df: pd.DataFrame, threshold: float = 3.0) -> pd.DataFrame:
    '''使用离群值上个月的数据替换所有离群值
    
    Args:
        df: 输入数据框
        threshold: Z-score阈值，默认为3.0
    '''
    try:
        # 计算用电量的Z值
        z_scores = np.abs(stats.zscore(df.iloc[:, 1]))
        
        # 获取离群值的索引
        outlier_indices = np.where(z_scores > threshold)[0]
        outlier_count = len(outlier_indices)
        
        if outlier_count > 0:
            # 对每个离群值，用其上个月的数据替换
            for idx in outlier_indices:
                if idx > 0:  # 确保不是第一个数据点
                    df.iloc[idx, 1] = df.iloc[idx-1, 1]
            print(f"pre_replace: 替换了{outlier_count}个离群值")
        return df
    except Exception as e:
        print(f"pre_replace替换处理错误: {str(e)}")
        return None